
package brian.huang.reader;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipFileUtils {
    private static final String TAG = "UnZip";
    private String mZipFile;
    private String mLocation;

    public ZipFileUtils(String location, String zipFile) {
        mZipFile = zipFile;
        File file = new File(zipFile);
        mLocation = location + "/" + file.getName() + "_" + file.lastModified();
    }

    public String getEntry(String entryName) {
        boolean exist = checkDir("");
        if (!exist) {
            unzip();
        }

        String result = mLocation + "/" + entryName;
        return result;
    }

    private void unzip() {
        try {
            FileInputStream fin = new FileInputStream(mZipFile);
            ZipInputStream zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
                String outputPath = mLocation + "/" + ze.getName();
                File file = new File(outputPath);
                file.getParentFile().mkdirs();

                if (ze.isDirectory()) {
                    continue;
                }
                FileOutputStream fout = new FileOutputStream(outputPath);
                byte[] buffer = new byte[2048];
                int count;
                while ((count = zin.read(buffer)) != -1) {
                    fout.write(buffer, 0, count);
                }

                fout.close();
            }
            zin.close();
        } catch (Exception e) {
            Log.e(TAG, "unzip", e);
        }
    }

    private boolean checkDir(String dir) {
        boolean exist = false;
        File f = new File(mLocation + dir);

        if (f.exists()) {
            exist = true;
        } else {
            f.mkdir();
        }
        return exist;
    }
}
